"""
支付相关异步任务
"""
from datetime import datetime, timedelta
from sqlalchemy.orm import Session
from loguru import logger

from utils.celery_app import celery_app
from utils.database import SessionLocal
from utils.comm import get_ali_object
from Models.travel.models import Order
from Models.travel.payment_models import Payment, PaymentStatus


def get_db_session() -> Session:
    """获取数据库会话"""
    return SessionLocal()


@celery_app.task(name="tasks.payment_tasks.query_payment_status")
def query_payment_status(payment_id: int):
    """
    查询支付状态（用于主动查询未收到回调的支付）
    
    Args:
        payment_id: 支付记录ID
    """
    db = get_db_session()
    try:
        payment = db.query(Payment).filter(Payment.id == payment_id).first()
        if not payment:
            logger.warning(f"支付记录不存在: {payment_id}")
            return
        
        # 如果已经成功或失败，不需要查询
        if payment.status in [PaymentStatus.SUCCESS, PaymentStatus.FAILED, PaymentStatus.CLOSED]:
            logger.info(f"支付已完成，无需查询: {payment.payment_no}")
            return
        
        # 调用支付宝查询接口
        # 注意：新的支付模块的 query_pay 方法返回的是签名字符串，需要调用支付宝API才能获取结果
        # 这里暂时跳过主动查询，等待回调通知
        # TODO: 实现通过支付宝API查询订单状态的功能
        logger.info(f"支付状态查询功能待实现: {payment.payment_no}")
        return
    except Exception as e:
        logger.error(f"查询支付状态异常: {e}", exc_info=True)
        db.rollback()
    finally:
        db.close()


@celery_app.task(name="tasks.payment_tasks.check_expired_payments")
def check_expired_payments():
    """
    检查过期的支付订单并关闭
    定时任务，建议每5分钟执行一次
    """
    db = get_db_session()
    try:
        now = datetime.now()
        # 查询过期且未完成的支付
        expired_payments = db.query(Payment).filter(
            Payment.status.in_([PaymentStatus.PENDING, PaymentStatus.PROCESSING]),
            Payment.expired_at < now
        ).all()
        
        for payment in expired_payments:
            try:
                # 新的支付模块暂不支持主动查询和取消订单
                # 直接关闭过期的支付记录
                payment.status = PaymentStatus.CLOSED
                db.commit()
                logger.info(f"关闭过期支付: {payment.payment_no}")
                
                # TODO: 实现通过支付宝API查询和取消订单的功能
                # alipay = get_ali_object()
                # query_string = alipay.query_pay(out_trade_no=payment.order_no)
                # # 需要调用支付宝API获取实际结果并处理
            except Exception as e:
                logger.error(f"处理过期支付失败: {payment.payment_no}, 错误: {e}", exc_info=True)
                db.rollback()
        
        logger.info(f"检查过期支付完成，处理了 {len(expired_payments)} 条记录")
    except Exception as e:
        logger.error(f"检查过期支付异常: {e}", exc_info=True)
        db.rollback()
    finally:
        db.close()


@celery_app.task(name="tasks.payment_tasks.sync_payment_status")
def sync_payment_status():
    """
    同步支付状态（对账任务）
    定时任务，建议每小时执行一次
    """
    db = get_db_session()
    try:
        # 查询处理中或待支付的订单（创建时间在24小时内）
        cutoff_time = datetime.now() - timedelta(hours=24)
        payments = db.query(Payment).filter(
            Payment.status.in_([PaymentStatus.PENDING, PaymentStatus.PROCESSING]),
            Payment.created_at >= cutoff_time
        ).all()
        
        # 新的支付模块暂不支持主动查询订单状态
        # TODO: 实现通过支付宝API查询订单状态的功能
        logger.info("支付状态同步功能待实现，等待回调通知")
        success_count = 0
        
        # 以下代码暂时注释，等待实现查询接口
        # alipay = get_ali_object()
        # for payment in payments:
        #     try:
        #         query_string = alipay.query_pay(out_trade_no=payment.order_no)
        #         # 需要调用支付宝API获取实际结果
        #         result = None  # 需要实现API调用
        #         if not result:
        #             continue
        #         
        #         trade_status = result.get("trade_status")
        #         if trade_status == "TRADE_SUCCESS" or trade_status == "TRADE_FINISHED":
        #             if payment.status != PaymentStatus.SUCCESS:
        #                 payment.status = PaymentStatus.SUCCESS
        #                 payment.third_party_trade_no = result.get("trade_no")
        #                 payment.paid_at = datetime.now()
        #                 
        #                 order = db.query(Order).filter(Order.id == payment.order_id).first()
        #                 if order and order.status == "pending":
        #                     order.status = "paid"
        #                     order.paid_at = datetime.now()
        #                 
        #                 db.commit()
        #                 success_count += 1
        #                 logger.info(f"同步支付状态成功: {payment.payment_no}")
        #         elif trade_status == "TRADE_CLOSED":
        #             if payment.status != PaymentStatus.CLOSED:
        #                 payment.status = PaymentStatus.CLOSED
        #                 db.commit()
        #                 logger.info(f"同步支付状态为关闭: {payment.payment_no}")
        #     except Exception as e:
        #         logger.error(f"同步支付状态失败: {payment.payment_no}, 错误: {e}", exc_info=True)
        #         db.rollback()
        
        logger.info(f"同步支付状态完成，更新了 {success_count} 条记录")
    except Exception as e:
        logger.error(f"同步支付状态异常: {e}", exc_info=True)
        db.rollback()
    finally:
        db.close()



